package project3;

import java.net.*;
import java.io.*;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;

/*
 * Loop reads from buffer and writes to socket
 * Null objects read from the buffer are discarded 
 */

public class WriterThread extends Thread {
	private boolean dead;
	private BlockingQueue<Cell> buffer;
	private DataOutputStream out;
	private static final int POLL_INTERVAL = 100;
	
	public WriterThread(BlockingQueue<Cell> buffer, Socket sock) {
		this.dead = false;
		this.buffer = buffer;		
		
		try {			
			out = new DataOutputStream(sock.getOutputStream());
		} catch (Exception e) {
			System.err.println("DataOutputStream constructor threw an exception");
			e.printStackTrace();
		}
	}

	
	public void run() {
		while (!dead) {
			// loop read from buffer and write to socket
			Cell toBeSent = null;
			
			try {
				toBeSent = buffer.poll(POLL_INTERVAL, TimeUnit.MILLISECONDS);
			} catch (InterruptedException e) {
				e.printStackTrace();
				continue;
			}
			
			if (toBeSent != null) {
				try {
					out.write(toBeSent.generateByteData());
				} catch (IOException e) {
					e.printStackTrace();
				}
			}			
		}
	}
}
